<?php
namespace app\common\job;
use Sanyc\Aliyun\AliyunEmail;
use think\queue\Job;
use think\Log;
use Carbon\Carbon;
use think\Db;
class JobPay{
    protected $user_table = 'users';
    protected $camp_table = 'camps';
    protected $car_table  = 'caravan';
    private   $config     = ['mail' => [
        'accessKey' => 'gw9QdAPaIsYjR1Uu', 
        'accessSecret' => 'dyOOXvGW0Q6bG05Agr7hXJCr5wdBDd', 
        'accountName' => 'hy@m.shsytour.cn', 
        'fromAlias' => '双辉'
    ]];
    /**
     * 处理充值
     * @param  Job    $job  [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
	public function recharge(Job $job, $data){
        if ($orderinfo = model('user/Intergrateadds')->getOrderInfo(['order_num' => $data])) {
            if ($orderinfo->paid_at) {
                $job->delete();
            }else{
                $d = controller('user/Payment')->getS($data);
                if ($d->trade_state == 'SUCCESS' && $d->return_code == 'SUCCESS' && $d->result_code == 'SUCCESS') {
                    if ($orderinfo->completeOrderPay($data)) {
                        $job->delete();
                    } 
                }
            }
        }      
    }
    
    /**
     * 处理房车订单
     * @param  Job    $job  [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function order(Job $job, $data){
        if ($orderinfo = model('user/Orders')->getOrderInfo(['number' => $data])) {
            if ($orderinfo->paid_at) {
                $job->delete();
            }else{
                $d = controller('user/Payment')->getS($data);
                if ($d->trade_state == 'SUCCESS' && $d->return_code == 'SUCCESS' && $d->result_code == 'SUCCESS') {
                    if ($orderinfo->completeOrderPay($data)) {
                        $job->delete();
                    } 
                }
            }
        }  
    }
    public function sendEmailTest(Job $job, $data)
    {
        if ($this->sendWhichUser($data['number'],$data['qufen'])) {
            $job->delete();
        }else{
            if ($job->attempts() > 2) {
                $job->delete();
            }
        }
        
    }

    public function changeRentMoneyBase(Job $job, $data)
    {
        try {
            $camp_info      = model('user/Camps')->get($data);
            $caravan_ids    = $camp_info->carvans()->column('id');
            $calendar_model = model('user/Calendar');
            $caravan_info   = model('user/CaravanInfos')->getCaravanInfo($data);
            $money_base     = $camp_info->rent_money_base;

            foreach ($caravan_ids as $caravan_id) {
                if ($calendars = $calendar_model->all(['caravan_id' => $caravan_id, 'datetimes' => ['>=', Carbon::now()->toDateString()]])) {
                    foreach ($calendars as $calendar) {
                        if ($calendar->shares && $calendar->rents && $calendar->locks) {
                            $calendar->single_day_price = $money_base * $calendar->getCoefficient($calendar->datetimes);
                            $calendar->save();
                        }
                    }
                }
            }
            $job->delete();
            
        } catch (\Exception $e) {
            Log::record($e->getMessage());
        }
        
    }

    public function sendMail(Job $job, $data)
    {
        if ($this->sendWhichUser($data)) {
            # code...
        }
        if ($orderinfo = model('user/Orders')->getOrderInfo(['number' => $data])) {
            if ($orderinfo->paid_at) {
                $job->delete();
            }else{
                $d = controller('user/Payment')->getS($data);
                if ($d->trade_state == 'SUCCESS' && $d->return_code == 'SUCCESS' && $d->result_code == 'SUCCESS') {
                    if ($orderinfo->completeOrderPay($data)) {
                        $job->delete();
                    } 
                }
            }
        }
    }

    
    public function failed($data){
    
          echo "超出";
    }

    /**
     * [sendWhichUser 发送邮件]
     * @param  [type] $type         [description]
     * @param  [type] $order_number [description]
     * @return [type]               [description]
     */
    protected function sendWhichUser($order_number,$qufen)
    {
        $theme = '双辉旅程网';
        $o_t = ['1'=>'出租','2'=>'交换'];
        $orderinfo  = model("user/Orders")->where('number',$order_number)->find();
        $type       = $orderinfo->source;
        $xia_dan    = $orderinfo->created_at;//halt($xia_dan);
        $start_date = $orderinfo->take_car_date;
        $end_date   = $orderinfo->leave_car_date;
        $User = db($this->user_table, $config = [], $force = false);
        try {
        switch ($qufen) {
            case 'user':
            //下单人邮箱
            $user_email = $User->where('id',$orderinfo->rent_user_id)->value('email');
            $content2  = <<<data
尊敬的会员，您于 $xia_dan 下单并支付成功。$o_t[$type]日期是 $start_date 至 $end_date ,祝您旅途愉快。
data;
            $this->sendEmail($user_email,$theme,$content2);
                break;
            case 'car':
            //车主邮箱
            $car_email = $User->where('id',$orderinfo->caravan_user_id)->value('email');
            $content1  = <<<data
尊敬的会员，您的房车于 $xia_dan 被他人下单。$o_t[$type]日期是 $start_date 至 $end_date 。
data;
            $this->sendEmail($car_email,$theme,$content1);
                break;
            case 'camp':
            //通知营地信息
            $camp_email = db($this->camp_table)->where('id',$orderinfo->camp_id)->value('email');
            $car_name = db($this->car_table)->where('id',$orderinfo->caravan_id)->value('name');
            $content3  = <<<data
尊敬的营地管理员， 于 $xia_dan ,该营地房车：$car_name 被他人预定 。预定日期是 $start_date 至 $end_date 。
data;
            $this->sendEmail($camp_email,$theme,$content3);
                break;    
            default:
                # code...
                break;
            }
        }catch (\Exception $e) {
           return false; 
        }
        return true;
    }

    /**
     * [sendEmail 发送邮箱]
     * @param  [type] $emailAddress [目标邮箱]
     * @param  [type] $theme        [邮件主题]
     * @param  [type] $content      [邮件内容]
     * @return [type]               [description]
     */
    public function sendEmail($emailAddress,$theme,$content)
    {
        $mail = AliyunEmail::init($this->config['mail'])->send($emailAddress, $theme, $content);
        return $mail;
    }
    /**
     * [WishNotice 心愿通知]
     * @param Job    $job  [description]
     * @param [type] $data [心愿详情]
     */
    public function WishNotice(Job $job, $data)
    {
        $theme = '双辉旅程网';//trace($content1);一个助手函数用于日志记录
        //发布方所在地区所有会员
        $camp_id =Db::table($this->camp_table)->where('area',$data['0']['city'])->column('id');
        //判断是否有
        if (!empty($camp_id)) {
        $users_id = Db::table($this->user_table)->where(['camp_id'=>['in',$camp_id]])->column('id');
        //判断是否有
        if (!empty($users_id)) {
        foreach ($users_id as $user_id) {
         try{
            $users = Db::table($this->user_table)->where('id',$user_id)->find();
            //车主邮箱
            $car_email = $users['email'];
            $w         = $users['wh_accpet'];trace($w);
            $start_date= $data['0']['start_date'];
            $end_date  = $data['0']['end_date'];
            if ($w) {
            $content1  = <<<data
尊敬的会员，您所在地区有人发布心愿。发布日期是 $start_date 至 $end_date 。
data;
            $this->sendEmail($car_email,$theme,$content1);   
            }
           $job->delete(); 
           }catch (\Exception $e) {
            if ($job->attempts() > 2) {
                $job->delete();
            }
           }
          }
         }
        }

    }
    /**
     * [ReceiveWish 接收心愿]
     * @param Job    $job  [description]
     * @param [type] $data [接单方车id,发布方用户email]
     */
    public function ReceiveWish(Job $job,$data)
    {
        $theme   = '双辉旅程网'; 
        //满足方房车信息、营地、位置
        try{
        $Carvan_info = Db::table($this->car_table)->where('id',$data['caravan_id'])->find();
        //trace($Carvan_info);
        $name        = $Carvan_info['name'];
        $camp_id     = $Carvan_info['services'];
        $Camp_info   = Db::table($this->camp_table)->where('id',$camp_id)->find();
        $camp_name   = $Camp_info['name'];
        $camp_address= $Camp_info['address'];
        //邮件内容
        $content1  = <<<data
尊敬的会员，您所发布的心愿有人接单。车的名称是 $name ; 所在营地 $camp_name ;详细地址为$camp_address 。
data;
        $this->sendEmail($data['email'],$theme,$content1);
        $job->delete();
        }catch (\Exception $e) {
            if ($job->attempts() > 2) {
                $job->delete();
            }
        }
    }

}